<?php

namespace app\api\middleware;

use app\api\common\ApiAuth;
use app\api\common\Auth;
use app\api\common\common;
use app\api\exception\BaseException;
use think\facade\Db;
use think\facade\Request;


class CheckApi
{
    public function handle($request, \Closure $next)
    {
        $response = $next($request);
        $common = new common();
        // 添加中间件执行代码
        $header = $request->header();
        $apiAuthList = ApiAuth::getApiList();
        $rootList = array_merge_recursive($apiAuthList["root"], $apiAuthList["admin"], $apiAuthList["finance"], $apiAuthList["user"], $apiAuthList["base"]);
        $adminList = array_merge_recursive($apiAuthList["admin"], $apiAuthList["finance"], $apiAuthList["user"], $apiAuthList["base"]);
        $financeList = array_merge_recursive($apiAuthList["finance"],$apiAuthList["user"] ,$apiAuthList["base"]);
        $userList = array_merge_recursive($apiAuthList["user"], $apiAuthList["base"]);
        $baseList = $apiAuthList["base"];

        if (in_array(request()->pathinfo(), $baseList)) {
            return $response->header();
        } else {
            $tokeninfo = Db::name("permission")->where(["sign" => $header["sign"], "data_state" => 1])->find();

            //管理员

            if ($tokeninfo){
                if ($tokeninfo["user_type"] == 2) {
                    if (in_array(request()->pathinfo(), $adminList)) {
                        return $response->header();
                    } else {
                        return $common->result(request()->pathinfo(), '拒绝访问', '100001');
                    }
                }

                //财务
                if ($tokeninfo["user_type"] == 3) {
                    if (in_array(request()->pathinfo(), $financeList)) {
                        return $response->header();
                    } else {
                        return $common->result(null, '拒绝访问', '100001');
                    }
                }
                if ($tokeninfo["user_type"] == 4) {

                    if (in_array(request()->pathinfo(), $userList)) {
                        return $response->header();
                    } else {
                        return $common->result(null, '拒绝访问', '100001');
                    }
                }
            }else{
                return $common->result(null, '请先登录', '100001');
            }

        }
        return $response->header();
    }

}